package com.example.mvcdemo.controller;

import com.example.mvcdemo.model.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/3
 * Time: 11:41
 */
//@RestController
@RequestMapping("/response")

@Controller
// @Controller(返回页面) + @ResponseBody == @RestController
// @ResponseBody(返回数据) 既是类注解又是方法注解
// 加在类上，表示该类的所有方法都返回数据
// 加在方法上，表示该方法返回数据，其他的方法不受影响
public class ResponseController {
    @RequestMapping("/returnHtmlPage")
    public String returnHtmlPage() {
        return "/hello.html";
    }

    @ResponseBody
    @RequestMapping("/returnData")
    public String returnData() {
        return "abcdefgh";
    }

    @ResponseBody
    @RequestMapping("/returnHtml")
    public String returnHtml() {
        return "<h1>returnHtml</h1>";
    }

    // 返回 json
    @ResponseBody
    @RequestMapping("/returnJson")
    public User returnJson() {
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setGender("男");
        return user;
    }

    // 设置状态码
    @ResponseBody
    @RequestMapping("/setStatus")
    public User setStatus(HttpServletResponse response) {
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setGender("男");
        response.setStatus(500);
        return user;
    }

    @ResponseBody
    @RequestMapping(value = "/setHeader", produces = "application/json")
    public String setHeader() {
        return "{\"success\":true}";
    }

    @ResponseBody
    @RequestMapping("/setHeader2")
    public String setHeader2(HttpServletResponse response) {
        response.setHeader("myKey", "myValue");
        // 设置 Cookie
        Cookie cookie = new Cookie("key", "value");
        response.addCookie(cookie);
        return "success";
    }
}
